#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

void stream_write()
{
    FILE *fp = fopen("test_fopen.txt", "w");
    if (fp == NULL)
    {
        perror("fopen");
        return ;
    }

    int count = 0;
    while (1)
    {
        printf("count = %d\n", count);
        fprintf(fp, "count = %d\n", count);
        sleep(1);
        count++;
    }
}

void linux_write()
{
    int fd = open("test_open.txt", O_WRONLY|O_CREAT, 0644);
    if (fd < 0)
    {
        perror("open fail");
        return ;
    }

    int count = 0;
    char buf[64];
    int len;
    while (1)
    {
        printf("count = %d\n", count);
        len = snprintf(buf, sizeof(buf), "count = %d\n", count);
        write(fd, buf, len);
        sleep(1);
        count++;
    }
}

int main()
{
    printf("1 测试流式文件\n 2. 测试linux文件\n");
    char c = getchar();
    if (c == '1')
        stream_write();
    else if (c == '2')
        linux_write();

    return 0;
}

/* 测试1: 流式文件
SIGINT, SIGTERM 都没有刷新缓冲区，导致文件内容没有写入

 */

/* 测试2: linux文件
系统调用write 一直刷新缓冲区，所以文件内容正常写入

*/